<template>
  <base-modal
    class="spartpart-dialog-container"
    :title="$t('common.form.preview.sparepart.title2')"
    :show.sync="visible"
    width="700px"
  >
    <el-table
      v-if="visible"
      ref="multipleTable"
      header-row-class-name="base-table-header-v3"
      row-class-name="base-table-row-v3"
      @select="handleSelection"
      @select-all="handleSelection"
      :data="data"
      border>
      <el-table-column
        type="selection"
        align="center"
        width="40"
        :selectable="selectable"
      ></el-table-column>
      <el-table-column
        v-for="(column, index) in columns"
        :key="`${column.fieldName}_${index}`"
        :label="column.displayName"
        :prop="column.fieldName"
        show-overflow-tooltip
        :min-width="column.minWidth">
        <template slot-scope="scope">
          <!-- start 规格 -->
          <template v-if="column.fieldName === 'relationStandard'">
            {{ scope.row.standard || '' }}
          </template>
          <!-- end 规格 -->

          <!-- start 小计 -->
          <template v-if="column.fieldName === 'total'">
            {{ scope.row.salePrice && (scope.row.preNum * scope.row.salePrice).toFixed(2) }}
          </template>
          <!-- end 小计 -->

          <!-- start 出库仓库 -->
          <template v-else-if="column.fieldName === 'repertoryName'">
            <template v-if="scope.row.sparePartUseNum || personalRepertory">
              <template v-if="scope.row.sparePartUseNum">
                <template v-if="isOpenData && scope.row.sparePartOutRepertoryStaffId">
                  <open-data type='userName' :openid="scope.row.sparePartOutRepertoryStaffId"></open-data>
                </template>
                <template v-else>
                  {{scope.row.sparePartOutRepertoryName}}
                </template>
              </template>
              <template v-else>
                <template v-if="isOpenData && scope.row.repertoryStaffId">
                  <open-data type='userName' :openid="scope.row.repertoryStaffId"></open-data>
                </template>
                <template v-else>
                  {{scope.row.repertoryName}}
                </template>
              </template>
            </template>
            <el-select
              @change="chooseRepertory($event, scope.row, scope.$index)"
              v-model="scope.row.repertoryId"
              v-else>
              <el-option
                v-for="item in scope.row.repertorys"
                :key="item.repertoryId"
                :label="item.repertoryName"
                :value="item.repertoryId">
              </el-option>
            </el-select>
          </template>
          <!-- end 出库仓库 -->

          <!-- start 备件去向 -->
          <template v-else-if="column.fieldName === 'sparePartInRepertoryName'">
            <!-- start 已出库的备件 -->
            <template v-if="scope.row.sparePartUseNum">
              <template v-if="scope.row.sparePartInRepertoryId">
                <template v-if="isOpenData && scope.row.sparePartInRepertoryStaffId">
                  <open-data type='userName' :openid="scope.row.sparePartInRepertoryStaffId"></open-data>
                </template>
                <template v-else>
                  {{scope.row.sparePartInRepertoryName}}
                </template>
              </template>
              <template v-else>
                {{$t('common.form.preview.sparepart.des7')}}
              </template>
            </template>
            <!-- end 已出库的备件 -->

            <template v-else>-</template>
          </template>
          <!-- end 备件去向 -->

          <!-- start 可用数量 -->
          <template v-else-if="column.fieldName === 'sparePartUseNum'">
            <!-- start 已出库的备件 -->
            <template v-if="scope.row.sparePartUseNum">
              {{ scope.row.sparePartInRepertoryId ? scope.row.repertoryCount : scope.row[column.fieldName] }}
            </template>
            <!-- end 已出库的备件 -->

            <template v-else>-</template>
          </template>
          <!-- end 可用数量 -->

          <template v-else>{{ scope.row[column.fieldName] }}</template>
        </template>
      </el-table-column>
      <el-table-column :label="$t('common.form.preview.sparepart.des8')" prop="usedNum" width="110px" show-overflow-tooltip :render-header="renderUsedNumHeader" v-if="allowPartOut">
        <template slot-scope="scope">
          {{ scope.row.sparePartUseNum ? scope.row.usedNum : '-' }}
        </template>
      </el-table-column>
    </el-table>
    <div class="tips">{{$t('common.form.preview.sparepart.des9')}}</div>

    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">{{$t('common.base.cancel')}}</el-button>
      <el-button type="primary" @click="submit">{{$t('common.base.submit')}}</el-button>
    </div>
  </base-modal>
</template>

<script>
/* util */
import * as _ from 'lodash';
import { isOpenData } from '@src/util/platform'
import i18n from '@src/locales'
export default {
  name: 'sparepart-list-dialog',
  props: {
    fields: {
      type: Array,
      default: () => ([])
    },
    data: {
      type: Array,
      default: () => ([])
    },
    value: {
      type: Array,
      default: () => ([])
    },
    allowPartOut: {
      type: Boolean,
      default: false
    },
    personalRepertory: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      isOpenData,
      visible: false,
      multipleSelection: []
    }
  },
  computed: {
    columns() {
      let fields = this.fields.filter(field => field.enabled && !field.isHidden);
      fields = [
        ...fields,
        {
          displayName: i18n.t('common.form.preview.sparepart.colum9'),
          fieldName: 'repertoryName',
          minWidth: '140px'
        }
      ]

      // 开启出库申请
      if (this.allowPartOut) {
        fields.push({
          displayName: i18n.t('common.form.preview.sparepart.colum10'),
          fieldName: 'sparePartInRepertoryName',
          minWidth: '100px'
        }, {
          displayName: i18n.t('common.form.preview.sparepart.colum11'),
          fieldName: 'sparePartUseNum'
        })
      }

      return fields;
    },
    /** 
    * @description 当前登录账户
    */
    loginUserName() {
      let { displayName } = window?.parent?.loginUser || {};
      return displayName;
    }
  },
  methods: {
    /**
    * @description 打开弹窗
    */
    open() {
      this.data.map(item => {
        let { id, repertoryCount } = item.personalRepertory || {};
        let isOncePartOut = item.sparePartUseNum > 0; // 是否已出库备件
        let isOutRepertoryPart = isOncePartOut && !item.sparePartInRepertoryId; // 是否直接出库

        // 初始化仓库
        item.repertoryId = '';
        item.repertoryName = '';

        // 开启个人备件库且不是直接出库
        if (this.personalRepertory && !isOutRepertoryPart) {
          item.repertoryName = this.loginUserName;
          item.number = this.getNumber(repertoryCount, item.preNum);
          item.repertoryCount = repertoryCount;
          item.id = id;
        }

        // 开启出库申请 且 已直接出库
        if (this.allowPartOut && isOutRepertoryPart) {
          item.id = `${item.sparePartId}_${item.sparePartOutRepertoryId}`; // 唯一标识
          item.repertoryName = item.sparePartOutRepertoryName;
          item.repertoryId = item.sparePartOutRepertoryId;
          item.repertoryCount = item.sparePartUseNum;
          item.number = item.sparePartUseNum;
          item.spType = 0;
        }
      })

      // 清空选中数据
      this.multipleSelection = [];
      this.visible = true;
    },
    // 判断是否禁用勾选
    selectable(row) {
      // 开启个人备件库时 未出库的备件判断个人库是否有库存
      let { repertoryCount } = row.personalRepertory || {};
      let isOutRepertoryPart = row.sparePartUseNum && !row.sparePartInRepertoryId; // 是否直接出库
      if (this.personalRepertory && !isOutRepertoryPart) return repertoryCount > 0;

      return true;
    },
    /**
    * @description 勾选列表数据
    */
    handleSelection(selection) {
      this.multipleSelection = selection;
    },
    /**
    * @description 提交
    */
    submit() {
      if (!this.multipleSelection.length) return this.$platform.alert(this.$t('common.form.tip.sparepart.tips1'));

      // 仓库必填校验
      let isEmptyRepertoryArr = this.multipleSelection.filter(item => !item.repertoryName);
      if (isEmptyRepertoryArr.length) return this.$platform.alert(this.$t('common.form.tip.sparepart.tips1', {data1:isEmptyRepertoryArr[0].name}));

      // 查找已添加的备件中是否存在该备件
      this.multipleSelection.forEach(item => {
        let idx = this.value.findIndex(val => val.id == item.id && val.salePrice == item.salePrice);
        // 不存在
        if (idx == -1) this.value.push(_.cloneDeep(item));
      })

      this.visible = false;
    },
    /**
    * @description 选择仓库
    */
    chooseRepertory(value, row, index) {
      let currentRepertory = row.repertorys.find(item => item.repertoryId == value);
      row.repertoryName = currentRepertory.repertoryName;
      row.repertoryCount = currentRepertory.repertoryCount;
      row.number = this.getNumber(row.repertoryCount, row.preNum); // 用量
      row.id = currentRepertory.id; // 备件仓库关联id

      this.$set(this.data, index, row);
    },
    getNumber(maxNum, preNum) {
      return maxNum > preNum ? preNum : maxNum;
    },
    renderUsedNumHeader(h, { column }) {
      return ([
        column.label,
        h('el-tooltip', {
          props: {
            placement: 'top-end',
            content: i18n.t('common.form.tip.sparepart.tips3')
          }
        }, [
          h('i', {
            class: 'iconfont icon-question'
          })
        ])
      ])
    }
  }
}
</script>

<style lang="scss" scoped>
.spartpart-dialog-container {
  ::v-deep .base-modal-body {
    padding: 16px 24px;
  }

  .el-table {
    ::v-deep .el-checkbox {
      width: auto;
      line-height: 40px;
      margin-bottom: 0;
      padding: 0;
    }

    ::v-deep .el-table-column--selection {
      .cell {
        padding-right: 10px !important;
      }
    }

    ::v-deep .icon-question {
      font-size: $font-size-small;
      color: $text-color-regular;
      margin-left: 4px;
    }
  }

  .tips {
    font-size: $font-size-small;
    color: $text-color-regular;
  }
}
</style>